<template>
  <div>
    <el-card class="box-card" shadow="never">
      <div slot="header" class="clearfix">
        <span class="card-title"></span>
        <span style="float: left"
          ><el-upload
            :action.sync="fileUploadUrl"
            :limit="1"
            :on-success="hanldeFileUploadSucess"
            :show-file-list="false"
            ref="file"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload></span
        >
        <span style="float: left; margin-left: 10px"
          ><el-button type="danger" size="small" @click="handleDelete">{{
            $t("common.delete")
          }}</el-button></span
        >
      </div>
      <div class="text item">
        <el-table
          ref="table"
          :data="attachments"
          tooltip-effect="dark"
          style="width: 100%"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column label="日期" width="160">
            <template slot-scope="scope">{{
              scope.row.creationTime | datetime
            }}</template>
          </el-table-column>
          <el-table-column prop="fileName" label="文件名" width="120">
            <template slot-scope="scope">{{ scope.row.fileName }}</template>
          </el-table-column>
          <el-table-column prop="fileExtension" label="格式">
            <template slot-scope="scope">{{
              scope.row.fileExtension
            }}</template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                @click.native.prevent="
                  handleDownload(
                    scope.row.remoteFileId,
                    scope.row.contentType,
                    scope.row.fileName + scope.row.fileExtension
                  )
                "
                type="text"
                size="small"
              >
                下载
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>
<script>
import {
  getAttachments,
  addAttachment,
  deleteAttachment,
} from "@/api/attachment";

import { downloadFile } from "@/api/file";
export default {
  data() {
    return {
      attachments: [],
      baseUrl: "",
    };
  },
  methods: {
    getData() {
      if (!this.ownerId) return;

      getAttachments({
        moduleCode: this.moduleCode,
        ownerId: this.ownerId,
        pageIndex: 1,
        pageSize: 100000,
      }).then((res) => {
        this.attachments = !res ? [] : res.items;
      });
    },
    hanldeFileUploadSucess(response) {
      if (!response) {
        this.$notify({
          title: "失败",
          message: "文件上传失败",
          type: "error",
          position: "bottom-right",
        });
        return;
      }
      this.$refs.file.clearFiles();

      let attachment = {
        ownerId: this.ownerId,
        moduleCode: this.moduleCode,
        fileName: response.fileName,
        fileExtension: response.fileExtension,
        remoteFileId: response.id,
      };

      this.hanldeAddAttachment(attachment);
    },
    hanldeAddAttachment(attachment) {
      addAttachment(attachment).then((res) => {
        this.getData();
      });
    },
    handleDelete() {
      let selectedDatas = this.$refs.table.selection;
      if (!selectedDatas || selectedDatas.length == 0) {
        this.$alert(this.$t("tips.noSelectedRow"), this.$t("common.tips"), {
          confirmButtonText: this.$t("common.ok"),
        });
        return;
      }
      this.$confirm(this.$t("tips.confirmDelete"), this.$t("common.tips"), {
        confirmButtonText: this.$t("common.ok"),
        cancelButtonText: this.$t("common.cancel"),
        type: "warning",
      })
        .then(() => {
          let ids = selectedDatas.map((data) => {
            return data.id;
          });
          for (let i = 0; i < ids.length; i++) {
            deleteAttachment(ids[i]).then((res) => {
              if (!res) return;
              if (i == ids.length - 1) {
                this.$notify({
                  title: "成功",
                  message: "删除成功",
                  type: "success",
                  position: "bottom-right",
                });
                this.getData();
              }
            });
          }
        })
        .catch(() => {});
    },
    handleDownload(fileId, contentType, name) {
      downloadFile({ id: fileId }).then((res) => {
        let blob = new Blob([res], {
          type: contentType,
        });
        let link = document.createElement("a");
        link.href = window.URL.createObjectURL(blob);
        link.download = name;
        link.click();

        window.URL.revokeObjectURL(link.href);
      });
    },
  },
  mounted() {
    this.baseUrl = process.env.VUE_APP_BASE_API;
    this.getData();
  },
  computed: {
    fileUploadUrl() {
      return this.baseUrl + "api/v1/files";
    },
  },
  props: {
    moduleCode: {
      type: String,
      default: "",
    },
    ownerId: {
      type: String,
      default: "",
    },
  },
};
</script>
<style scoped></style>
